/*!
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *
 *    Author: flareguner
 *    E-Mail: flareguner@gmail.com
 *    Years: 2010-2010
 */


static const int timeout = 1000;

#include "hackedtextedit.h"
#include <QtGui/QMenu>
#include <QtGui/QAction>
#include <QtGui/QTextDocumentFragment>
#include <QtGui/QContextMenuEvent>
#include <QtGui/QKeyEvent>
#include <QtCore/QTimer>

HackedTextEdit::HackedTextEdit(QWidget *parent) :
    QTextEdit(parent),
    m_add_sequence(new QAction(tr("Add exception"), this)),
    m_release_timer(new QTimer(this))
{
    m_add_sequence->setDisabled(true);
    connect(m_add_sequence, SIGNAL(triggered()), this, SLOT(emitSelectedText()));
    connect(this, SIGNAL(selectionChanged()), this, SLOT(updateHaveSelection()));
    connect(m_release_timer, SIGNAL(timeout()),this,SIGNAL(inputFinished()));
    connect(m_release_timer, SIGNAL(timeout()),m_release_timer,SLOT(stop()));
    

}

void HackedTextEdit::contextMenuEvent(QContextMenuEvent *e){
    QMenu *menu = createStandardContextMenu();
    menu->addAction(m_add_sequence);
    menu->exec(e->globalPos());
    delete menu;
}

void HackedTextEdit::emitSelectedText(){
    emit hasReserverdSequence(this->textCursor().selection().toPlainText());
}

void HackedTextEdit::updateHaveSelection(){
    m_add_sequence->setEnabled(!this->textCursor().selectedText().isEmpty());
}

void HackedTextEdit::keyReleaseEvent(QKeyEvent *e) {
    e->accept();
    m_release_timer->stop();
    m_release_timer->start(timeout);
}
